<?php

include_once("interface.php");

//Main
$test = 0;
$pp = 0;

if ( $_SERVER['argv'][1] == "test") {
    $test = 1;
    $method = $_SERVER['argv'][2];
    $pp = $_SERVER['argv'][3];
    $module = $_SERVER['argv'][4];
}
else {
    $method = $_GET['m'];
    $pp = $_GET['pp'];
    $module = $_GET['module'];
    error_log("Main: method=$method, pretty=$pp, module=$module");
}

try {
    $o = ModuleFactory::createModule($module);
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

if ( $method == "get" ) {
    if($o) {
        if($pp == 1) {
            $str = print_r($o->readDataFromSystem(), true);
            print("<pre>".$str."</pre>\n");
        }
        else {
            $jsonstr = $o->getJSON();
            print($jsonstr);
        }
    }
}
else if ( $method == "set" ) {
    if($test) {
        $jsonstr = file_get_contents("php://stdin");
    }
    else {
        $jsonstr = file_get_contents("php://input");
    }
    error_log("Main: received $jsonstr for module=$module\n");

    if($o && $jsonstr) {
        $ret = $o->setJSON($jsonstr);
        error_log("Main: ret from setJSON: ".$ret);
        print($ret);
    }
}
else if ( $method == "commit" ) {
    if($o) {
        print($o->commitDataToSystem(null));
    }
}
else if ( $method == "html" ) {
    if($o) {
        print("<html>");
        print("<head>");
        print($o->printHeader());
        print($o->printHeaderScript());
        print($o->printModuleScript());
        print("</head>\n");
        print("<body>\n");
        print($o->printBody());
        print("<div class='rightPane'>\n");
        print($o->printModuleHTML());
        print("</div>\n");
        print("</body>\n");
        print("</html>\n");
    }
}
?>
